
#include "muduo/proto/dispatcher.h"
#include "muduo/proto/codec.h"
#include "request.pb.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include"muduo/net/EventLoopThread.h"
#include"muduo/base/CountDownLatch.h"
#include<iostream>

class Client
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
    typedef std::shared_ptr<xiang11::AddResponse> AddResponsePtr;
    typedef std::shared_ptr<xiang11::TranslateResponse> TranslateResponsePtr;

    Client(const std::string& sip, int port)
        :_latch(1)
        ,_client(_loopthread.startLoop(), muduo::net::InetAddress(sip, port), "Client")
        ,_dispatcher(std::bind(&Client::onUnknownMessage,
         this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
        ,_codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, 
         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        //注册业务请求处理函数 
        _dispatcher.registerMessageCallback<xiang11::TranslateResponse>(std::bind(&Client::onTranslate, this,
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _dispatcher.registerMessageCallback<xiang11::AddResponse>(std::bind(&Client::onAdd, this,
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec,
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        _client.setConnectionCallback(std::bind(&Client::onConnection, this,
        std::placeholders::_1));
    }
    //需要等待链接成功后再返回 阻塞等待用latch
    void connect()
    {
        _client.connect();  //会直接返回
        _latch.wait();      //阻塞等待 直到链接成功
    }
    void Translate(const std::string &msg)
    {
        xiang11::TranslateRequest req;
        req.set_msg(msg);
        send(&req);
    }
    void Add(int num1, int num2)
    {
        xiang11::AddRequest req;
        req.set_num1(num1);
        req.set_num2(num2);
        send(&req);
    }

private:
    bool send(const google::protobuf::Message *message)
    {
        if (_conn->connected())
        { // 连接状态正常，再发送，否则就返回false
            _codec.send(_conn, *message);
            return true;
        }
        return false;
    }
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            _conn = conn;       //先赋值 否则会主线程先跑
            
            _latch.countDown(); //唤醒主线程阻塞
        }
        else
        {
            //链接关闭时的操作
            _conn.reset();
        }
    }
    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateResponsePtr &message, muduo::Timestamp)
    {
        std::cout << "Translate result: " << message->msg() << std::endl;

    }
    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddResponsePtr &message, muduo::Timestamp)
    {
        std::cout << "Add result: " << message->result() << std::endl;   
    }
        //收到消息时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        std::cout << "翻译结果：" << buf->retrieveAllAsString() << std::endl;
    }
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }
private:
    muduo::CountDownLatch _latch;                   //实现同步
    muduo::net::EventLoopThread _loopthread;        //异步循环处理线程
    muduo::net::TcpClient _client;                  //客户端
    muduo::net::TcpConnectionPtr _conn;             //客户对应链接
    ProtobufDispatcher _dispatcher;                 //分发器
    ProtobufCodec _codec;                           //协议处理器
};


int main()
{
    Client client("127.0.0.1", 8899);
    client.connect();

    while(1)
    {
        client.Translate("hello");
        client.Add(11, 22);
        sleep(1);
    }

    sleep(1);
    
    return 0;
}